﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KXCXW.Web.CommonClass;
using System.IO;
using System.Drawing;
using kxcxw.Data;
using System.Data;
using System.Data.SqlClient;
using kxcxw.Data.Entities;
using kxcxw.Data.Common;
using System.Data.Entity.Validation;

namespace KXCXW.Web.Areas.Admin.Controllers
{
    public class ImageController : Controller
    {
        private KXCXWDBContext db = new KXCXWDBContext();
        private ImgHelper conlist = null;
        //
        // GET: /Admin/Image/
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult Index()
        {
            //AddDate();
            //AddImages();
            return View();
        }

        private void AddDate()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=kxcxw_access;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=true");
            con.Open();
            SqlCommand cmd = new SqlCommand(@"select 发布人=(case when info_fabuzhe='chengfan' then 'f6fbb43a-08ea-47e0-833e-8ef5def23455'
when info_fabuzhe='qijinwen' then '185d57f6-6eef-4026-baec-f1e2e6b53eee'
when info_fabuzhe='zdy_servers' then 'cc3a7fa2-a49e-46ee-80b7-31db3e972993'
when info_fabuzhe='sql2018' then 'ca2a15c6-a598-4b43-bb77-8eb4771cf595'
when info_fabuzhe='wendengyun' then 'e0a25cb7-27dd-496b-9d52-5e3b193510a4'
else '4acf66a9-a750-4462-bce7-54d501bc23be' end),title=info_title,品牌=info_cx_pinpai,intoType=case when info_web_shop<>'' then 1 else 2 end,category=info_p03type,info_cuxiao,discount=info_jizhe,
原价=info_yuanjia,
现价=(case when info_xianjia='' then info_cx_price else info_xianjia end),
购增=info_fabuzhe,赠品=info_gouzeng,促销价=info_cx_price,shopurl=info_web_shop,
shiti=info_shiti_shop,简介=info_beizhu,电话=info_tel,联系人=info_name,QQ=info_qq,封面图=img_01,
图片集=case when img_01<>'' then '<imgs><filename>'+img_01+'</filename></imgs>' 
when img_02<>'' then '<imgs><filename>'+img_01+'</filename><filename>'+img_02+'</filename></imgs>' 
when img_03<>'' then '<imgs><filename>'+img_01+'</filename><filename>'+img_02+'</filename><filename>'+img_03+'</filename></imgs>' 
when img_04<>'' then '<imgs><filename>'+img_01+'</filename><filename>'+img_02+'</filename><filename>'+img_03+'</filename><filename>'+img_04+'</filename></imgs>' 
when img_05<>'' then '<imgs><filename>'+img_01+'</filename><filename>'+img_02+'</filename><filename>'+img_03+'</filename><filename>'+img_04+'</filename><filename>'+img_05+'</filename></imgs>' 
when img_06<>'' then '<imgs><filename>'+img_01+'</filename><filename>'+img_02+'</filename><filename>'+img_03+'</filename><filename>'+img_04+'</filename><filename>'+img_05+'</filename><filename>'+img_06+'</filename></imgs>' 
else '' end,发布时间=info_time,访问次数=info_hits
from dbo.kx_info where info_cuxiao not in('新品','积分')
                    ", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                PublichInformation pif = new PublichInformation();
                pif.InformationID = Guid.NewGuid().ToString();
                pif.Title = dr["title"].ToString();
                pif.Brand = dr["品牌"].ToString();
                pif.Other = "开心促销网开心共分享";
                if (dr["info_cuxiao"].ToString() == "购赠")
                {
                    pif.PromotionType = DataConstants.BuyAdd;
                    pif.Other = dr["赠品"].ToString();
                }
                if (dr["info_cuxiao"].ToString() == "其它")
                    pif.PromotionType = DataConstants.PriceReduction;
                if (dr["info_cuxiao"].ToString() == "清仓")
                    pif.PromotionType = DataConstants.Clearance;
                if (dr["info_cuxiao"].ToString() == "热卖")
                    pif.PromotionType = DataConstants.PanicBuying;
                if (dr["info_cuxiao"].ToString() == "折扣")
                    pif.PromotionType = DataConstants.Discount;
                string categoryname = dr["category"].ToString();
                var category = (from q in db.SysItemDetials
                                where q.itemDetialName == categoryname
                                select q).FirstOrDefault();
                pif.ItemDeitalID = category.ItemDeitalID;
                if (dr["原价"] != null && dr["原价"].ToString() != "")
                    pif.OriginalPrice = Convert.ToDecimal(dr["原价"].ToString());
                else
                    pif.OriginalPrice = 0;
                if (dr["现价"] != null && dr["现价"].ToString() != "")
                    pif.PresentPrice = Convert.ToDecimal(dr["现价"].ToString());
                else
                    pif.PresentPrice = 0;
                if (dr["discount"] != null && dr["discount"].ToString() != "")
                    pif.Discount = Convert.ToDecimal(dr["discount"].ToString());
                else
                    pif.Discount = 1;
                pif.ShopUrl = dr["shopurl"].ToString() == "" ? "http://kxcxw.com" : dr["shopurl"].ToString();
                pif.Addres = dr["shiti"].ToString() == "" ? "开心促销网开心共分享" : dr["shiti"].ToString();
                pif.Desception = dr["简介"].ToString();
                pif.Mobile = dr["电话"].ToString();
                pif.ContactPerson = dr["联系人"].ToString();
                pif.IM = dr["QQ"].ToString();
                pif.MapUrl = dr["封面图"].ToString();
                pif.PictureShow = dr["图片集"].ToString();
                pif.PublishDate = Convert.ToDateTime(dr["发布时间"].ToString());
                pif.InfoType = Convert.ToInt32(dr["intoType"].ToString());
                pif.Status = 1;
                pif.PublishID = dr["发布人"].ToString();
                pif.VisitsNumber = Convert.ToInt64(dr["访问次数"].ToString());
                db.PublichInformations.Add(pif);
                if (ModelState.IsValid)
                {
                    try
                    {
                        db.SaveChanges();
                        // 写数据库
                    }
                    catch (DbEntityValidationException dbEx)
                    {
                    }
                }
            }
        }
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult AddImages()
        {
            string path = @"E:\projects\kxcxw_old\pic";
            GetFileInfo(path);
            return View();
        }
        private void initImgPoth()
        {
            string rootpath = Server.MapPath("~/Content/xml/imgconfig.xml");
            conlist = new ImgHelper(rootpath);
        }
        private void GetFileInfo(string filePath)
        {

            List<string> all = new List<string>();
            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            try
            {
                //foreach (DirectoryInfo childDirectoryInfo in directoryInfo.GetDirectories())
                //{
                //    string name = childDirectoryInfo.Name.ToString();
                //    GetFileInfo(filePath + "\\" + childDirectoryInfo.Name.ToString());
                //}
                initImgPoth();
                foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                {
                    foreach (Img img in conlist.getImgConfigList())
                    {
                        string filename = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.'));
                        SavePicFormat(img.foldname, filename, img.width, img.height, Image.FromFile(fileInfo.FullName));
                    }
                }
            }
            catch
            {

            }
        }
        private void SavePicFormat(string folder, string thumbnail_id, int target_width, int target_height, Image jpeg_image_upload)
        {
            System.Drawing.Image original_image = null;
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            try
            {
                original_image = jpeg_image_upload;
                int width = original_image.Width;
                int height = original_image.Height;
                int new_width, new_height;
                float target_ratio = (float)target_width / (float)target_height;
                float image_ratio = (float)width / (float)height;

                if (target_ratio > image_ratio)
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }
                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;

                final_image = new System.Drawing.Bitmap(target_width, target_height);
                string url = Server.MapPath("~/" + ImgHelper.ImgRootUrl + folder + "/");
                graphic = System.Drawing.Graphics.FromImage(final_image);
                graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, target_width, target_height));
                int paste_x = (target_width - new_width) / 2;
                int paste_y = (target_height - new_height) / 2;
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */

                graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);

                final_image.Save(url + thumbnail_id + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            }
            finally
            {
                // Clean upF:\KXCXW_Project\KXCXW\KXCXW.Web\Content\swfupload\handlers.js
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
            }

        }
    }
}
